package io.gitee.heis.vehicle.race.sample01;


import java.text.DecimalFormat;

class Race01 {

   private final static char DONE_SYMBOL='_';
   /**
    * 赛道长度
    */
   private int barLen=80;

   /**
    * 用于赛道显示的字符
    */
   private String showChar="\uD83D\uDE97";

   private V3Vehicle01 vehicle;

   /**
    * 使用系统标准输出，显示字符赛道及其百分比
    */
   public Race01() {
   }

   /**
    * 显示赛道
    */
   public void show(long value,long startTime) {
       if (value < 0 || value > 100) {
           return;
       }
       reset();
       // 比例
       float rate = (float) (value*1.0 / 100);
       // 比例*赛道总长度=当前长度
       draw(barLen, rate,startTime);
       if (value == 100L) {
           afterComplete();
       }
   }

  /**
   * 绘制汽车竞赛
   * @param barLen 赛道长度
   * @param rate 完成赛道百分比
   * @param startTime 开始时间
   */
   private void draw(int barLen, float rate,long startTime) {
       int len = (int) (rate * barLen);
       System.out.print(vehicle.getEngine().getName()+"|");
       for (int i = 0; i < barLen-len; i++) {
           System.out.print(" ");
       }
       System.out.print(showChar);
       for (int i = 0; i < len; i++) {
           System.out.print(DONE_SYMBOL);
       }
       double timeCost=(System.currentTimeMillis()-startTime)/1000;
       System.out.print(" |" + format(rate)+", "+timeCost+"秒");
   }

   /**
    * 光标移动到行首
    */
   private void reset() {
       System.out.print('\r');
   }

   /**
    * 完成后换行
    */
   private void afterComplete() {
       System.out.print('\n');
   }

   private String format(float num) {
       return new DecimalFormat("#.##%").format(num);
   }

   public void start() throws InterruptedException {
       long startTime=System.currentTimeMillis();
       for (int i = 1; i <= 100; i++) {
           show(i,startTime);
           Thread.sleep(10000/vehicle.getPower());
       }
   }

   public void setVehicle(V3Vehicle01 vehicle) {
       this.vehicle = vehicle;
   }
}